# -*- coding: utf-8 -*-
from typing import Any
from .common import session_begin
from sqlalchemy.orm import Session
from utility.security import get_password_hash, verify_password
from app.yg_crm.schemas import User, UserCreate, UserUpdate
from app.yg_crm.orm import User as DB_User


@session_begin
def create_user(db: Session, user_create: UserCreate) -> User:
    user = User(** user_create.model_dump(exclude_unset=True, exclude_none=True))
    db.add(user)
    db.refresh(user)
    return user


@session_begin
def update_user(db: Session, db_user: DB_User, user_in: UserUpdate) -> Any:
    user_data = user_in.model_dump(exclude_unset=True, exclude_none=True)
    for field in user_data:
        if "password" == field:
            password = user_data["password"]
            db_user.hashed_password = get_password_hash(password)
        else:
            setattr(db_user, field, user_data[field])

    db.refresh(db_user)
    return db_user


@session_begin
def get_user(db: Session, user_id: str):
    res = db.query(DB_User).filter(DB_User.id == user_id).scalar()
    return res


@session_begin
def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(DB_User).all()


@session_begin
def get_user_by_email(db: Session, email: str) -> DB_User | None:
    return db.query(DB_User).filter(DB_User.email == email).first()


@session_begin
def get_user_by_username(db: Session, username: str):
    return db.query(DB_User).filter(DB_User.username == username).first()


def authenticate(db: Session, email: str, password: str) -> User | None:
    db_user = get_user_by_email(db=db, email=email)
    if not db_user:
        return None
    if not verify_password(password, db_user.hashed_password):
        return None
    return db_user


